﻿using HrEFCore;
using HrEFCore.Models;
using HrIService;
using HrService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Printing;
using System.Text.Json;

namespace HrUI.Controllers
{
    public class EMRController : Controller
    {
        private EMRService eMRService;
        private readonly CFTKService cFTKService;
        private readonly CMKService cMKService;
        private readonly CMService cMService;
        private readonly IDistributedCache distributedCache;
        private readonly ILogger<HomeController> logger;
        private readonly MyDbContext myDbContext;

        public EMRController(MyDbContext myDbContext, EMRService eMRService, CFTKService cFTKService, CMKService cMKService,
            CMService cMService, IDistributedCache distributedCache, ILogger<HomeController> logger)
        {
            this.eMRService = eMRService;
            this.cFTKService = cFTKService;
            this.cMKService = cMKService;
            this.cMService = cMService;
            this.distributedCache = distributedCache;
            this.logger = logger;
            this.myDbContext = myDbContext;
        }
        public async Task<IActionResult> IndexAsync()
        {
            string uname = HttpContext.Session.GetString("UTrueName");
            ViewBag.uname = uname;
            await xllb();
            return View();
        }
        public async Task<IActionResult> XG(short Id)
        {
            //跳转XG页面
            EMRViewXG eMRAllAsync = await eMRService.EMRViewXGAllAsync(Id);
            ViewData.Model = eMRAllAsync;
            return View();
        }
        public async Task<IActionResult> EMRUpdate(EMR eMR)
        {
            string uname = HttpContext.Session.GetString("UTrueName");
            eMR.Changer = uname;
            eMR.ChangeTime= DateTime.Now;
            int row = await eMRService.ReviseEMR(eMR);
            if (row > 0)
            {
                return RedirectToAction("Revise");
            }
            else
            {
                return View();
            }
        }
        public async Task xllb()//下拉列表
        {
            List<CFFK> list = await cFTKService.CFFKSelectAsync();
            SelectList selectListItems = new SelectList(list, "FirstKindId", "FirstKindName");
            ViewBag.cffk = selectListItems;//一级

            List<CFSK> list2 = await cFTKService.CFSKSelectAsync();
            SelectList selectListItems1 = new SelectList(list2, "SecondKindId", "SecondKindName");
            ViewBag.cfsk = selectListItems1;//二级

            List<CFTK> list3 = await cFTKService.SelectCFTKAsync();
            SelectList selectListItems2 = new SelectList(list3, "ThirdKindId", "ThirdKindName");
            ViewBag.cftk = selectListItems2;//三级

            List<CMK> list4 = await cMKService.InquireAll();
            SelectList selectListItems3 = new SelectList(list4, "MajorKindId", "MajorKindName");
            ViewBag.cmk = selectListItems3;//职位分类

            List<CM> list5 = await cMService.CMSelectAsync();
            SelectList selectListItems4 = new SelectList(list5, "MajorId", "MajorName");
            ViewBag.cm = selectListItems4;//职位名称
        }
        [HttpPost]
        public async Task<IActionResult> Add(EMR emr)//添加
        {
            CFFK cffk = await cFTKService.CFFKByIdAsync(emr.FirstKindId);
            emr.FirstKindName = cffk.FirstKindName;//一级

            CFSK cfsk = await cFTKService.CFSKByIdAsync(emr.SecondKindId);
            emr.SecondKindName = cfsk.SecondKindName;

            CFTK cftk = await eMRService.cftkById(emr.FirstKindId);
            emr.ThirdKindName = cftk.ThirdKindName;

            CMK cmk = await eMRService.SelectCMKById(emr.MajorKindId);
            emr.MajorKindName = cmk.MajorKindName;//职位分类
            
            CM cm = await eMRService.SelectCMById(emr.MajorId);
            emr.MajorName = cm.MajorName;//职位名称

            int row = await eMRService.AddEMR(emr);
            if (row > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        public async Task<List<JiLian>> GetFirstKinds()
        {
            List<CFFK> cf = await cFTKService.CFFKSelectAsync();
            List<JiLian> jl = new List<JiLian>();
            foreach (CFFK item in cf)
            {
                JiLian jilian = new JiLian()
                {
                    value = item.FirstKindId,
                    label = item.FirstKindName,
                    children = await GetSecondKinds(item.FirstKindId)
                };
                jl.Add(jilian);
            }
            return jl;
        }
        public async Task<List<JiLian>> GetSecondKinds(string id)
        {
            List<CFSK> cs = await cFTKService.CFSKLDAsync(id);
            List<JiLian> jl = new List<JiLian>();
            foreach (CFSK item in cs)
            {
                JiLian jiLian = new JiLian()
                {
                    value = item.SecondKindId,
                    label = item.SecondKindName,
                    children = await GetThirdKinds(item.SecondKindId)
                };
                jl.Add(jiLian);
            }
            return jl;
        }
        public async Task<List<JiLian>> GetThirdKinds(string id)
		{
			List<CFTK> cf= await cFTKService.CFTKLDAsync(id);
			List<JiLian> jl = new List<JiLian>();
			foreach (CFTK item in cf)
			{
				JiLian jiLian = new JiLian()
				{
					value = item.ThirdKindId,
					label = item.ThirdKindName,
				};
				jl.Add(jiLian);
			}
			return jl;
		}
        
        public async Task<IActionResult> PostsName(short Id)
        {
            //根据ID查询EMR数据,跳转
            //List<EMR> eMRAllAsync = await eMRService.EMRAllAsyncSY(Id);
            List<EMR> eMRAllAsync = new List<EMR>();
            string bid = "Rosel" + Id;
            string book = await distributedCache.GetStringAsync(bid);
            if (book==null)
            {
                logger.LogInformation("从数据库查询");

                eMRAllAsync = await eMRService.EMRAllAsyncSY(Id);   // 数据库查询

                DistributedCacheEntryOptions distributedCacheEntryOptions = new DistributedCacheEntryOptions();
                distributedCacheEntryOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(15);

                distributedCache.SetString(bid, JsonSerializer.Serialize(eMRAllAsync), distributedCacheEntryOptions);
            }

            else
            {
                logger.LogInformation("从缓存中查询");
                eMRAllAsync = JsonSerializer.Deserialize<List<EMR>>(book);
            }

            ViewData.Model = eMRAllAsync;
            return View();
        }
        public async Task<ActionResult> DeleteAsync(string id)
        {
            short mreId;
            if (!short.TryParse(id, out mreId))
            {
                // ID格式不正确，返回职位分类列表，并提示用户
                Content("<script>alert('参数错误！')</script>");
                return RedirectToAction("Index");
            }
            int result = await eMRService.DeleteEMR(mreId);
            if (result > 0)
            {
                // 删除成功
                Content("<script>alert('删除成功！')</script>");
            }
            else
            {
                // 删除失败，返回职位分类列表，并提示用户
                Content("<script>alert('删除失败！')</script>");
            }
            return RedirectToAction("Revise");
        }
        public IActionResult Revise(int page = 1, int pageSize = 1)
        {
            var result = eMRService.GetPagedEMRView(page, pageSize);
            ViewData.Model = result;

            // 设置分页相关数据
            ViewData["CurrentPage"] = page;
            ViewData["PageSize"] = pageSize;
            ViewData["TotalRows"] = myDbContext.EMRView.Count();

            return View();
        }
        [HttpGet]
        public IActionResult FYCX(int page, int pageSize)
        {
            var result = eMRService.GetPagedEMRView(page, pageSize);

            return Json(new { emrList = result, totalRows = myDbContext.EMRView.Count() });
        }
        public IActionResult Inquire(int page = 1, int pageSize = 1)
        {
            var result = eMRService.GetPagedEMRView(page, pageSize);
            ViewData.Model = result;

            // 设置分页相关数据
            ViewData["CurrentPage"] = page;
            ViewData["PageSize"] = pageSize;
            ViewData["TotalRows"] = myDbContext.EMRView.Count();

            return View();
        }
        //public IActionResult Inquire(int page)
        //{
        //    //职位发布查询
        //    int pageSize = 1; //每页显示的记录数
        //    string keyName = "MreId"; //关键字
        //    string tableName = "EMR"; //表名
        //    string where = ""; //查询条件
        //    int currentPage = page; //当前页码
        //    int totalRows; //总记录数
        //    //调用分页查询方法
        //    var emrList = eMRService.CallFenyeStoredProcedure(pageSize, keyName, tableName, where, currentPage, out totalRows);
        //    ViewData.Model = emrList;
        //    //计算总页数
        //    int totalPages = (int)Math.Ceiling((double)totalRows / pageSize);
        //    ViewData["PageSize"] = pageSize;
        //    ViewData["EMRList"] = emrList;
        //    ViewData["TotalPages"] = totalPages;
        //    ViewData["CurrentPage"] = currentPage;
        //    ViewData["TotalRows"] = totalRows;
        //    return View();
        //}
        //public IActionResult Revise(int page)
        //{
        ////职位发布变更
        //int pageSize = 1; //每页显示的记录数
        //string keyName = "MreId"; //关键字
        //string tableName = "EMR"; //表名
        //string where = ""; //查询条件and majorName like '%%' 
        //int currentPage = page; //当前页码
        //int totalRows; //总记录数
        ////调用分页查询方法
        //var emrList = eMRService.CallFenyeStoredProcedure(pageSize, keyName, tableName, where, currentPage, out totalRows);
        //ViewData.Model = emrList;
        ////计算总页数
        //int totalPages = (int)Math.Ceiling((double)totalRows / pageSize);
        //ViewData["PageSize"] = pageSize;
        //ViewData["EMRList"] = emrList;
        //ViewData["TotalPages"] = totalPages;
        //ViewData["CurrentPage"] = currentPage;
        //ViewData["TotalRows"] = totalRows;
        //return View();
    }
    //public IActionResult FYCX(int page,int Displayed)
    //    {
    //        //分页
    //        int pageSize = Displayed; //每页显示的记录数
    //        string keyName = "MreId"; //关键字
    //        string tableName = "EMR"; //表名
    //        string where = ""; //查询条件
    //        int currentPage = page; //当前页码
    //        int totalRows; //总记录数
    //        // 调用分页查询方法
    //        var emrList = eMRService.CallFenyeStoredProcedure(pageSize, keyName, tableName, where, currentPage, out totalRows);

    //        var result = new { emrList = emrList, totalRows = totalRows };
    //        return Json(result);
    //    }
    //}
}